package com.example.rabbitmq.topic.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;

/**
 * @Auther:
 * @Description: 主题交换机
 * @Date: 2019/12/27 11:32
 */
//@Configuration
public class TopicConfig {
    //绑定键
    public final static String KEY_MAN = "topic.man";
    public final static String KEY_WOMAN = "topic.woman";

    //定义 3 个队列
    @Bean
    public Queue manQueue() {
        return new Queue(TopicConfig.KEY_MAN);
    }

    @Bean
    public Queue womanQueue() {
        return new Queue(TopicConfig.KEY_WOMAN);
    }

    @Bean
    public Queue allQueue() {
        return new Queue("topic.all");
    }

    // 定义一个 topic 交换机， myTopicExchange
    @Bean
    public TopicExchange myTopicExchange() {
        return new TopicExchange("myTopicExchange");
    }

    //绑定 man 队列，
    // 这样只要消息携带的路由键是topic.man,就回分发到 man队列
    @Bean
    public Binding bindingManExchange() {
        return BindingBuilder.bind(manQueue()).to(myTopicExchange()).with(KEY_MAN);
    }

    //绑定 woman 队列，
    // 这样只要是消息携带的路由键是以topic.woman 开头,都会分发到该队列
    @Bean
    public Binding bindingWOmanExchange() {
        return BindingBuilder.bind(womanQueue()).to(myTopicExchange()).with(KEY_WOMAN);
    }

    //绑定 ALL 队列，
    // 这样只要是消息携带的路由键是以topic.开头,都会分发到该队列,因为上面两个的 RoutingKey 前面都有 topic. 所以给上面两个发消息是也会给这个发
    @Bean
    public Binding bindingAllExchange() {
        return BindingBuilder.bind(allQueue()).to(myTopicExchange()).with("topic.#");
    }
}
